package richbar.com.richbar.util;

import android.content.Context;
import android.content.SharedPreferences;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import richbar.com.richbar.bean.LoginBean;

/**
 * Created by QiYang on 2018/12/5.
 */

public class SpUtil {
    private final static String LOGIN_INFO_FILE = "login_info_file";
    private final static String LOGIN_INFO_TAG = "login_info_tag";
    public static void clearLoginInfo(Context context) {
        SharedPreferences sp = context.getSharedPreferences(LOGIN_INFO_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }


    public static void setLoginInfo(Context context, LoginBean loginBean){
        SharedPreferences sp = context.getSharedPreferences(LOGIN_INFO_FILE, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        String strJson = null;
        if (null != loginBean) {
            Gson gson = new Gson();
            //转换成json数据，再保存
            strJson = gson.toJson(loginBean);
        }
        editor.putString(LOGIN_INFO_TAG, strJson);
        editor.commit();
    }

    public static LoginBean getLoginInfo(Context context) {
        SharedPreferences sp = context.getSharedPreferences(LOGIN_INFO_FILE, Context.MODE_PRIVATE);
        LoginBean data = null;
        String strJson = sp.getString(LOGIN_INFO_TAG, null);
        if (null == strJson) {
            return data;
        }
        Gson gson = new Gson();
        data = gson.fromJson(strJson, new TypeToken<LoginBean>() {
        }.getType());
        return data;
    }
}
